package com.jinglvhuanjing.app.widget;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatTextView;
import androidx.constraintlayout.widget.ConstraintLayout;

import com.jinglvhuanjing.app.R;
import com.jinglvhuanjing.app.bean.LogEvent;
import com.jinglvhuanjing.app.bean.RunEvent;
import com.jinglvhuanjing.app.bean.SheetBottomBean;
import com.jinglvhuanjing.app.utils.ByteUtil;
import com.jinglvhuanjing.app.utils.LOG;
import com.jinglvhuanjing.app.utils.SerialMsgHandler;
import com.jinglvhuanjing.app.utils.SingletonSerl;
import com.jinglvhuanjing.app.utils.StringUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.io.IOException;
import java.text.DecimalFormat;
import java.util.ArrayList;

public class ParamSettingRow5SecView extends ConstraintLayout {

    private static final String TAG = "其他设置";

    private boolean getCQZ = true;
    /*** 选择投口 ***/
    private MySpinnerView spinner_config_tk;
    /*** 清除故障 ***/
    private ButtonView other_button1;
    /*** 0点校准 ***/
    private ButtonView other_button2;
    /*** 去皮 ***/
    private ButtonView other_button3;
    /*** 砝码校准值 ***/
    private CustomEdtView other_edt1;
    /*** 砝码校准按钮 ***/
    private ButtonView other_button4;
    /*** 模式选择 ***/
    private MySpinnerView other_spinner1;
    /*** 模式设置 ***/
    private ButtonView other_button5;
    /*** 正反转值 ***/
    private CustomEdtView other_edt2;
    /*** 模式设置 ***/
    private ButtonView other_button6;
    /*** 模式设置 ***/
    private ButtonView other_button7;

    public ParamSettingRow5SecView(@NonNull Context context) {
        super(context);
        this.init(context);
    }

    public ParamSettingRow5SecView(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        this.init(context);
    }

    public ParamSettingRow5SecView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.init(context);
    }

    /*** 解析收到的投口信息 ***/
    Handler mHandlerQt = new Handler(Looper.myLooper()) {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    String obj = (String) msg.obj;
                    if (!StringUtils.isEmpty(obj)) {
                        byte[] bytes_ = ByteUtil.hexStringToBytes(obj);
                        if (bytes_ != null && bytes_.length > 1) {
                            // 06 功能码，轮询信息返回
                            if (bytes_[1] == SingletonSerl.byte_gnm_cssz && bytes_.length > 7) {
                                LOG.e(TAG, "读取内容:" + obj);
                                parseByte(bytes_);
                            }if (bytes_[1] == SingletonSerl.byte_gnm_khsOrCy && bytes_.length > 7) {
                                LOG.e(TAG, "读取内容:" + obj);
                                parseByte(bytes_);
                            }
                        }
                    }
                    break;
                case 1:
                    if(getCQZ){
                        try {
                            SingletonSerl singletonSerl = SingletonSerl.getInstance();
                            SingletonSerl.getInstance().write(TAG, singletonSerl.cqz());
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        sendEmptyMessageDelayed(1, 2*1000);
                    }
                    break;
                default:
                    break;
            }
        }
    };

    @Subscribe
    public void onEvent(RunEvent event) {
        String hex = ByteUtil.hexBytesToString(event.getValue());
        LOG.e(SerialMsgHandler.TAG, TAG+"-读取内容:" + hex);
        Message message = this.mHandlerQt.obtainMessage();
        message.what = 0;
        message.obj = hex;
        this.mHandlerQt.sendMessage(message);
    }

    /**
     * @param bytes
     */
    public void parseByte(byte[] bytes) {
        LogEvent logEvent = new LogEvent();
        logEvent.setTAG(TAG);
        String jcqdz = ByteUtil.hexBytesToString(new byte[]{bytes[2], bytes[3]});
        String other = ByteUtil.hexBytesToString(new byte[]{bytes[4], bytes[5]});
        String other3 = "";
        if(bytes.length>9){
            other3 = ByteUtil.hexByteToString(bytes[8]);
        }
        String lx = SingletonSerl.getJCQDZLX_2(jcqdz, other, other3);
        if (!"未知".equals(lx)) {
            String bw = ByteUtil.hexBytesToString(bytes);
            logEvent.setValue(
                    String.format("【%s号投口】<%s>设置%s:%s"
                            , ByteUtil.hexByteToString(bytes[0])
                            , lx
                            , "成功"
                            , StringUtils.subStringToSpace(bw, 2))
            );
            EventBus.getDefault().post(logEvent);
        }
    }

    private void init(Context context) {
        getCQZ = true;
        LayoutInflater.from(context).inflate(R.layout.view_params_setting_row_5_sec_layout, this, true);
        spinner_config_tk = findViewById(R.id.spinner_config_tk);
        other_button1 = findViewById(R.id.other_button1);
        other_button2 = findViewById(R.id.other_button2);
        other_button3 = findViewById(R.id.other_button3);
        other_edt1 = findViewById(R.id.other_edt1);
        other_button4 = findViewById(R.id.other_button4);
        other_spinner1 = findViewById(R.id.other_spinner1);
        other_button5 = findViewById(R.id.other_button5);
        other_edt2 = findViewById(R.id.other_edt2);
        other_button6 = findViewById(R.id.other_button6);
        other_button7 = findViewById(R.id.other_button7);

        ArrayList<SheetBottomBean> items = new ArrayList<>();
        items.add(new SheetBottomBean("1号投口", ByteUtil.hexByteToString(SingletonSerl.byte_tk1)));
        items.add(new SheetBottomBean("2号投口", ByteUtil.hexByteToString(SingletonSerl.byte_tk2)));
        items.add(new SheetBottomBean("3号投口", ByteUtil.hexByteToString(SingletonSerl.byte_tk3)));
        items.add(new SheetBottomBean("4号投口", ByteUtil.hexByteToString(SingletonSerl.byte_tk4)));
        items.add(new SheetBottomBean("5号投口", ByteUtil.hexByteToString(SingletonSerl.byte_tk5)));
        spinner_config_tk.setData(items);

        ArrayList<SheetBottomBean> items2 = new ArrayList<>();
        items2.add(new SheetBottomBean("工作模式", "01"));
        items2.add(new SheetBottomBean("调试模式", "02"));
        other_spinner1.setData(items2);

        SerialMsgHandler.getInstance().setStartListener(true, this.mHandlerQt);
        EventBus.getDefault().register(this);
        setOnClick();
        this.mHandlerQt.sendEmptyMessage(1);
    }

    public void onDestroy() {
        getCQZ = false;
        try {
            EventBus.getDefault().unregister(this);
        }catch (Exception e){

        }
    }

    private void setOnClick() {
        other_button1.setOnClickListener(view -> {
            String tkDz = spinner_config_tk.getValue();
            if (!StringUtils.isEmpty(tkDz)) {
                try {
                    LOG.e(TAG, "开始清除障碍");
                    String bw = SingletonSerl.getInstance().write(TAG, SingletonSerl.otherSettingQCZA(tkDz));
                    eventBus(tkDz, "清除障碍", bw);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } else {
                Toast.makeText(getContext(), "请先选择投口地址", Toast.LENGTH_SHORT).show();
            }
        });

        other_button2.setOnClickListener(view -> {
            String tkDz = spinner_config_tk.getValue();
            if (!StringUtils.isEmpty(tkDz)) {
                try {
                    LOG.e(TAG, "开始0点校准");
                    String bw = SingletonSerl.getInstance().write(TAG, SingletonSerl.otherSettingJZ(tkDz));
                    eventBus(tkDz, "0点校准", bw);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } else {
                Toast.makeText(getContext(), "请先选择投口地址", Toast.LENGTH_SHORT).show();
            }
        });

        other_button3.setOnClickListener(view -> {
            String tkDz = spinner_config_tk.getValue();
            if (!StringUtils.isEmpty(tkDz)) {
                try {
                    LOG.e(TAG, "开始去皮");
                    String bw = SingletonSerl.getInstance().write(TAG, SingletonSerl.otherSettingQP(tkDz));
                    eventBus(tkDz, "去皮", bw);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } else {
                Toast.makeText(getContext(), "请先选择投口地址", Toast.LENGTH_SHORT).show();
            }
        });

        other_button4.setOnClickListener(view -> {
            String tkDz = spinner_config_tk.getValue();
            String fmjz = other_edt1.getText().toString().trim();
            if (!StringUtils.isEmpty(tkDz)) {
                if (!StringUtils.isEmpty(fmjz)) {
                    try {
                        LOG.e(TAG, "开始砝码校准");
                        String bw = SingletonSerl.getInstance().write(TAG, SingletonSerl.otherSettingFMJZ(tkDz,
                                ByteUtil.String_0(ByteUtil.intToHex(Integer.valueOf(fmjz)), 4)));
                        eventBus(tkDz, "砝码校准", bw);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                } else {
                    Toast.makeText(getContext(), "请先输入砝码值", Toast.LENGTH_SHORT).show();
                }
            } else {
                Toast.makeText(getContext(), "请先选择投口地址", Toast.LENGTH_SHORT).show();
            }
        });

        other_button5.setOnClickListener(view -> {
            String tkDz = spinner_config_tk.getValue();
            String mssz = other_spinner1.getValue();
            if (!StringUtils.isEmpty(tkDz)) {
                if (!StringUtils.isEmpty(mssz)) {
                    try {
                        LOG.e(TAG, "开始模式设置");
                        String bw = SingletonSerl.getInstance().write(TAG, SingletonSerl.otherSettingMSSZ(tkDz, mssz));
                        eventBus(tkDz, "模式设置", bw);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                } else {
                    Toast.makeText(getContext(), "请先选择模式", Toast.LENGTH_SHORT).show();
                }
            } else {
                Toast.makeText(getContext(), "请先选择投口地址", Toast.LENGTH_SHORT).show();
            }
        });

        other_button6.setOnClickListener(view -> {
            String tkDz = spinner_config_tk.getValue();
            String gmsj = other_edt2.getText().toString();
            if (!StringUtils.isEmpty(tkDz)) {
                if (!StringUtils.isEmpty(gmsj)) {
                    try {
                        LOG.e(TAG, "开始正转");
                        String bw = SingletonSerl.getInstance().write(TAG, SingletonSerl.otherSettingZFZ(tkDz,
                                ByteUtil.String_0(ByteUtil.intToHex(Integer.valueOf(gmsj)), 4),
                                true));
                        eventBus(tkDz, "正转", bw);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                } else {
                    Toast.makeText(getContext(), "请先输入关门时间", Toast.LENGTH_SHORT).show();
                }
            } else {
                Toast.makeText(getContext(), "请先选择投口地址", Toast.LENGTH_SHORT).show();
            }
        });

        other_button7.setOnClickListener(view -> {
            String tkDz = spinner_config_tk.getValue();
            String gmsj = other_edt2.getText().toString();
            if (!StringUtils.isEmpty(tkDz)) {
                if (!StringUtils.isEmpty(gmsj)) {
                    try {
                        LOG.e(TAG, "开始反转");
                        String bw = SingletonSerl.getInstance().write(TAG, SingletonSerl.otherSettingZFZ(tkDz,
                                ByteUtil.String_0(ByteUtil.intToHex(Integer.valueOf(gmsj)), 4),
                                false));
                        eventBus(tkDz, "反转", bw);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                } else {
                    Toast.makeText(getContext(), "请先输入关门时间", Toast.LENGTH_SHORT).show();
                }
            } else {
                Toast.makeText(getContext(), "请先选择投口地址", Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void eventBus(String tkdz, String type, String bw) {
        LogEvent logEvent = new LogEvent();
        logEvent.setTAG(TAG);
        logEvent.setValue(
                String.format("【%s号投口】<%s>发送:%s"
                        , ByteUtil.hexStringToInt(tkdz)
                        , type
                        , StringUtils.subStringToSpace(bw, 2)));
        EventBus.getDefault().post(logEvent);
    }

}
